﻿(function () {
    var ReadMarkContext = {};

    // You can provide templates for:
    // View, DisplayForm, EditForm and NewForm
    ReadMarkContext.Templates = {};
    ReadMarkContext.Templates.Fields = {
        "ReadMarkField": {
            "View": ReadMarkViewTemplate,
            "DisplayForm": RenderDisplayFormForReadMark
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(
        ReadMarkContext
        );
})();

// The ReadMarkViewTemplate provides the rendering logic
//  the custom field type when it is displayed in the view form.
function ReadMarkViewTemplate(ctx) {
    var readMarkId = ctx.listUrlDir.replace(/\//g, "_") + "$" + ctx.CurrentItem.ID + "$" + ctx.CurrentUserId;
    ctx.CurrentItem.Readed = readMarkId;
    ctx.CurrentItem.readMarkId = readMarkId;
    return "<span class='ReadMarkFiledPlaceHloderClass' id='" + readMarkId + "' >data loading</span>";
}

var readMarkIdForDisplayForm;
function RenderDisplayFormForReadMark(ctx)
{
    // var readMarkId = ctx.listUrlDir.replace(/\//g, "_") + "$" + ctx.CurrentItem.ID + "$" + ctx.CurrentUserId;
    // readMarkIdForDisplayForm = readMarkId + "DisplayFormForReadMark";

    // Insert one item into ReadList
    ExecuteOrDelayUntilScriptLoaded(InsertReadMarkItem, "sp.js");

    return "<span class='ReadMarkFiledPlaceHloderClass' id='readMarkIdPlaceHolderForDisplayForm' >data loading...</span>";
}

// user for storing current user object
var currentUser;
function InsertReadMarkItem()
{
    var ctx = SP.ClientContext.get_current();

    var currentweb = ctx.get_web();
    ctx.load(currentweb);
    currentUser = currentweb.get_currentUser();
    currentUser.retrieve();
    ctx.load(currentweb);
    ctx.executeQueryAsync(onLoadCurrentUserSuccessed, onLoadCurrentUserFailed);    
}

// Once load the current user successfully, then generate the read mark by list name + itemId + currentUserId
function onLoadCurrentUserSuccessed() {
    var currentUserId = currentUser.get_id();
    var itemId = getUrlParam("ID");
    var path = window.location.pathname;
    var index = path.lastIndexOf('/', path.length);
    var listPath = path.substring(0, index);

    var readMarkId = listPath.replace(/\//g, "_") + "$" + itemId + "$" + currentUserId;
    UpdateReadMarkItem(readMarkId);
}

// Insert the read mark into ReadList
function UpdateReadMarkItem(readMarkId) {
    var clientContext = new SP.ClientContext();
    var readList = clientContext.get_web().get_lists().getByTitle("ReadList");
    var itemCreateInfo = new SP.ListItemCreationInformation();
    var readItem = readList.addItem(itemCreateInfo);
    readItem.set_item("Title", readMarkId);
    readItem.update();

    clientContext.load(readItem);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, ReadMarkInsertSuccessed),
        Function.createDelegate(this, ReadMarkInsertFailed)
    );
}

function onLoadCurrentUserFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
    '\n' + args.get_stackTrace());
}

function ReadMarkInsertSuccessed()
{
    var readMarkIdPlaceHolderForDisplayForm = document.getElementById("readMarkIdPlaceHolderForDisplayForm");
    readMarkIdPlaceHolderForDisplayForm.innerText = "read";
}

function ReadMarkInsertFailed(sender, args) {
    alert('Request failed. ' + args.get_message() +
      '\n' + args.get_stackTrace());
}


function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

